package com.aspyn.finalproject;

import java.util.Stack;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;

import android.app.NotificationManager;
import android.content.ContentValues;
import android.content.Context; 
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.telephony.SmsManager;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

//HOWTO: ADD NEW PHRASES
/*
 1. Add phrases as items in ResFile.xml with name as phrase
 2. Add buttons in main.xml for the amount of phrases added
 3. Add the ids of the buttons added to the btnIDS array
 4. update numOfBtns
 5. Enjoy dat shit
 * */

public class FinalProjectActivity extends Activity implements OnClickListener {
	static TextView messageBox;
	static EditText msgField;
	final String kGhettoModePasscode = "GMP--?<>!QQ";
	boolean ghettoModeEnabled = false;
	final static String kDefaultNoMsgsStr = "No New Messages";

	Context aContext;

	static String msgBoxStr;

	static int NOTIFY_ME_ID = 0;

	static int msgCount = 0;//For note.number
	static int numOfMsgs = 0;

	final int numOfBtns = 39;

	final int[] btnIDS = {R.id.btn1,R.id.btn2,R.id.btn3,R.id.btn4,R.id.btn5,
			R.id.btn6,R.id.btn7,R.id.btn8,R.id.btn9,R.id.btn10,
			R.id.btn11,R.id.btn12,R.id.btn13,R.id.btn14,R.id.btn15,
			R.id.btn16, R.id.btn17, R.id.btn18, R.id.btn19, R.id.btn20, R.id.btn21,
			R.id.btn22, R.id.btn23, R.id.btn24, R.id.btn25, R.id.btn26, R.id.btn27,
			R.id.btn28, R.id.btn29, R.id.btn30, R.id.btn31, R.id.btn32, R.id.btn33,
			R.id.btn34, R.id.btn35, R.id.btn36, R.id.btn37, R.id.btn38, R.id.btn39};

	final Button[] btnArr = new Button[numOfBtns];

	final int numOfSmileys = 5;

	final int[] smileyIDS = {R.id.btnSmiley1,R.id.btnSmiley2,R.id.btnSmiley3,
			R.id.btnSmiley4,R.id.btnSmiley5};
	final Button[] smileyArr = new Button[numOfSmileys];
	String[] smileys = new String[numOfSmileys];

	String[] phrases = new String[numOfBtns];

	static String phoneNum;

	static Stack<TxtMsg> txtMsgStack = new Stack<TxtMsg>();

	public static final String PREFS_NAME = "MyPrefsFile";
	public static final String VIBRATE_PREF_NAME = "VibratePref";//0 is none, pattern # 
	static int vibrateNum;

	final static int vibratePatternLength = 6;
	final static long[] vibratePattern1 = {0L,100L,250L,1000L,250L,500L};
	final static long[] vibratePattern2 = {0L,50L,100L,500L,150L,5000L};
	static long[] currentVibratePattern = new long[vibratePatternLength];

	private int charsToUndo = 0;

	final String kHelpStr = "When you get a new text, you will get a notification " +
			"and if you press that notification you will be taken to Easy Reply so that you can easily respond by " +
			"tapping any one of the buttons, or by typing your message in the text field. If you would like to stop receiving notifications from this app, then uninstall this app.";
	final String kGhettoHelpStr = "When you get a new text, you need to reply to that homeboy " +
			"so that he doesn't fuck you up. Reply by " +
			"tapping any one of the buttons, or by typing your message in the text field. If you would like to stop receiving notifications from this app, then FUCK YOU!";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Set up screen
		//Remove title bar 
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.main);

		// Restore preferences
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		vibrateNum = settings.getInt(VIBRATE_PREF_NAME, 1);

		switch (vibrateNum) {
		case (0):
			currentVibratePattern[0] = -1;
		break;
		case (1):
			currentVibratePattern = vibratePattern1;
		break;
		case(2):
			currentVibratePattern = vibratePattern2;
		break;
		}

		//Set up messagebox and msgField
		messageBox = (TextView)findViewById(R.id.messageBox);
		updateMessageBox(" "," ");//Doesn't matter what is here because it is not stored bc no new texts-default msg displayed automatically, edit kDefaultNoMsgsStr to change
		msgField = (EditText)findViewById(R.id.msgField);

		//Set up phrase and smiley array
		phrases = getResources().getStringArray(R.array.phraseArray);
		smileys = getResources().getStringArray(R.array.SmileysArray);

		//Set up button array-Only set up the amount of buttons for the amt of phrases
		for (int i = 0; i<phrases.length; i++) {
			btnArr[i] = (Button)findViewById(btnIDS[i]);
			btnArr[i].setText(phrases[i]);
			btnArr[i].setOnClickListener(this);
		}

		//Set up smiley buttons array
		for (int i = 0; i<smileys.length; i++) {
			smileyArr[i] = (Button)findViewById(smileyIDS[i]);
			smileyArr[i].setText(smileys[i]);
			smileyArr[i].setOnClickListener(this);
		}

		//Set aContext to this
		aContext = this;

		//Set up don't reply button
		Button noRep = (Button)findViewById(R.id.noReply);
		noRep.setText("No Reply");

		noRep.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (numOfMsgs>0) {
					numOfMsgs--;
					if (numOfMsgs>0) {
						txtMsgStack.pop();
						TxtMsg txt = txtMsgStack.peek();
						updateMessageBox(txt.message,txt.sender);
						Toast.makeText(aContext, "No Reply", Toast.LENGTH_SHORT).show();
					}
					else {
						txtMsgStack.pop();
						updateMessageBox(" "," ");//Doesn't matter what is here because it is not stored bc no new texts
						Toast.makeText(aContext, "No Reply", Toast.LENGTH_SHORT).show();
					}
				}	
				else {
					updateMessageBox(" "," ");//Doesn't matter what is here because it is not stored bc no new texts
				}
			}

		});

		//Set up undo/clear buttons
		setUpFunctionButtons();

		//Set up send message button
		Button sendMsg = (Button)findViewById(R.id.btnSendText);
		sendMsg.setText("Send Text");

		sendMsg.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				//If text is ghettoMode passcode, enable/disable ghettoMode
				if (msgField.getText().toString().equals(kGhettoModePasscode)) {
					ghettoModeEnabled = !ghettoModeEnabled;
					msgField.setText("");
					charsToUndo = 0;
					if (ghettoModeEnabled) {
						setUpGhettoMode();
					}
					else {
						removeGhettoMode();
					} 
					return;
				}
				if (numOfMsgs>0) {
					txtMsgStack.pop();
					sendSMS(msgField.getText().toString());
				}		
				else {
					Toast.makeText(aContext, "There is no message to reply to", Toast.LENGTH_SHORT).show();
				}
			}

		});

	}

	public void setUpGhettoMode() {
		//Set up phrase and smiley array
		phrases = getResources().getStringArray(R.array.ghettoPhraseArray);

		//Set up button array-Only set up the amount of buttons for the amt of phrases
		for (int i = 0; i<phrases.length; i++) {
			btnArr[i] = (Button)findViewById(btnIDS[i]);
			btnArr[i].setText(phrases[i]);
			btnArr[i].setOnClickListener(this);
		}

		Toast.makeText(this, "Ghetto Mode Enabled", Toast.LENGTH_SHORT).show();
	}

	public void removeGhettoMode() {
		//Set up phrase and smiley array
		phrases = getResources().getStringArray(R.array.phraseArray);

		//Set up button array-Only set up the amount of buttons for the amt of phrases
		for (int i = 0; i<phrases.length; i++) {
			btnArr[i] = (Button)findViewById(btnIDS[i]);
			btnArr[i].setText(phrases[i]);
			btnArr[i].setOnClickListener(this);
		}

		Toast.makeText(this, "Ghetto Mode Disabled", Toast.LENGTH_SHORT).show();
	}

	public void setUpFunctionButtons() {
		Button btnUndo = (Button)findViewById(R.id.btnUndo);
		btnUndo.setText("Undo");

		btnUndo.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (charsToUndo<=msgField.getText().length()) {
					msgField.setText(msgField.getText().toString().substring(0, msgField.getText().length()-charsToUndo));
					charsToUndo = 0;
				}
			}

		});


		Button btnClear = (Button)findViewById(R.id.btnClear);
		btnClear.setText("Clear");

		btnClear.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				msgField.setText("");
				charsToUndo = 0;
			}

		});

		Button btnU = (Button)findViewById(R.id.btnU);
		btnU.setText("Add 'u?'");

		btnU.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				msgField.append("u?");
				charsToUndo = 2;
			}

		});
	}

	public void sendSMS(final String msg) {
		//Present confirm and option to add "u?"
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Send Text");
		alert.setMessage("Send " + "'" + msg + "' ?");

		final Context myContext = this;

		alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			TxtMsg txt = txtMsgStack.peek();
			public void onClick(DialogInterface dialog, int which) {
				PendingIntent pi = PendingIntent.getActivity(myContext, 0,
						new Intent(myContext, FinalProjectActivity.class), 0);
				SmsManager sms = SmsManager.getDefault();
				// this is the function that does all the magic
				sms.sendTextMessage(phoneNum, null, msg, pi, null);

				// store the sent sms in the sent folder (MAY NEED TO REMOVE THIS DEPENDING ON IF IT SHOULD BE HERE/ NOT EVERYONE USES STANDARD SMS APP) 
				/*ContentValues values = new ContentValues(); 
				values.put("address", phoneNum); 
				values.put("body", msg); 
				getContentResolver().insert(Uri.parse("content://sms/sent"), values);*/

				Toast.makeText(myContext, "Message Sent", Toast.LENGTH_SHORT).show();

				numOfMsgs--;
				updateMessageBox(txt.message,txt.sender);
			}
		});
		/*alert.setNeutralButton("Add 'u?'", new DialogInterface.OnClickListener() {
			TxtMsg txt = txtMsgStack.peek();
			public void onClick(DialogInterface dialog, int which) {
				PendingIntent pi = PendingIntent.getActivity(myContext, 0,
						new Intent(myContext, FinalProjectActivity.class), 0);
				SmsManager sms = SmsManager.getDefault();
				// this is the function that does all the magic
				sms.sendTextMessage(phoneNum, null, msg + " u?", pi, null);

				// store the sent sms in the sent folder (MAY NEED TO REMOVE THIS DEPENDING ON IF IT SHOULD BE HERE/ NOT EVERYONE USES STANDARD SMS APP) 
					ContentValues values = new ContentValues(); 
				values.put("address", phoneNum); 
				values.put("body", msg + " u?"); 
				getContentResolver().insert(Uri.parse("content://sms/sent"), values);


				Toast.makeText(myContext, "Message Sent", Toast.LENGTH_SHORT).show();


				numOfMsgs--;
				updateMessageBox(txt.message,txt.sender);
			}
		});*/
		alert.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(myContext, "Message Canceled", Toast.LENGTH_SHORT).show();
			}
		});
		alert.show();
	}

	@Override
	public void onResume() {
		super.onResume();
		NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

		if (txtMsgStack.size()>0)
			updateMessageBox(txtMsgStack.peek().message,txtMsgStack.peek().sender);

		mgr.cancel(NOTIFY_ME_ID);

		msgCount = 0;

		//Dismiss keyboard
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); 

	}

	public static void updateMessageBox(String msg, String phoneNumber)
	{
		if (numOfMsgs>0) {
			phoneNum = phoneNumber;
			msgBoxStr = "From: "+phoneNumber+"\n"+
					"Message: "+msg+"\n";
			messageBox.setText("From: "+phoneNumber+"\n"+
					"Message: "+msg+"\n");
		}
		else {
			messageBox.setText(kDefaultNoMsgsStr);
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		Button b = (Button)v;
		//		if (numOfMsgs>0) {
		msgField.append(b.getText() + " ");//Message and ' '(space)
		charsToUndo = b.getText().length()+1;//+1 is for space
		//		}
		/*		else {
			Toast.makeText(aContext, "There is no message to reply to", Toast.LENGTH_SHORT).show();
		}*/
	}

	//SETTINGS MENU
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.settingsmenu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case (R.id.svibratenone):
			vibrateNum = 0;
		saveVibratePref();
		return true;
		case (R.id.svibratep1):
			vibrateNum = 1;
		saveVibratePref();
		return true;
		case (R.id.svibratep2):
			vibrateNum = 2;
		saveVibratePref();
		return true;
		case (R.id.sabout):
			displayAbout();
		return true;
		case (R.id.shelp):
			displayHelp();
		return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void saveVibratePref() {
		switch (vibrateNum) {
		case (0):
			currentVibratePattern[0] = -1;
		break;
		case (1):
			currentVibratePattern = vibratePattern1;
		break;
		case(2):
			currentVibratePattern = vibratePattern2;
		break;
		}

		if (FinalProjectActivity.currentVibratePattern[0] != -1) {
			Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(FinalProjectActivity.currentVibratePattern, -1);
		}

		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt(VIBRATE_PREF_NAME, vibrateNum);

		// Commit the edits!
		editor.commit();

	}

	public void displayAbout() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("About");
		if (!ghettoModeEnabled) {
			alert.setMessage("Easy Reply: Created by Stuckinaboot Inc");
		}
		else {
			alert.setMessage("Created by White Boys With Swag");
		}
		alert.setPositiveButton("Cool",  null);
		alert.show();
	}

	public void displayHelp() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Help");
		if (!ghettoModeEnabled) {
			alert.setMessage(kHelpStr);
		}
		else {
			alert.setMessage(kGhettoHelpStr);
		}
		alert.setPositiveButton("Ok",  null);
		alert.show();
	}
}
